<template>
  <el-progress
    v-if="uploading"
    type="circle"
    :percentage="upload.percentage"
    :status="upload.status"
    :width="180"
  ></el-progress>
  <el-upload
    v-else
    class="avatar-uploader"
    action="https://jsonplaceholder.typicode.com/posts/"
    :http-request="diyUpload"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="value" :src="value" class="avatar" />
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    <div slot="tip" class="el-upload__tip">
      只能上传jpg/png文件，且不超过2MB
    </div>
  </el-upload>
</template>
<script lang="ts">
import { upload } from '@/services/course'
import { sleep } from '@/utils/helper'
import Vue from 'vue'
export default Vue.extend({
  // v-model
  props: ['value'],
  data () {
    return {
      uploading: false,
      upload: {
        percentage: 0,
        status: ''
      }
    }
  },
  // 进度条
  methods: {
    // v-model
    changeVal (val: string) {
      this.$emit('input', val)
    },
    uploadBegin () {
      this.changeVal('')
      this.uploading = true
      this.upload.percentage = 0
      this.upload.status = ''
    },
    uploadProgress (percentage: number) {
      this.upload.percentage = percentage
    },
    async uploadEnd (isSuccess: boolean, picUrl: string) {
      this.changeVal(picUrl)
      // 认为sucess表示上传成功，而不是进度100%
      this.upload.status = isSuccess ? 'success' : 'exception'
      await sleep(0.3)
      this.uploading = false
    },
    // 上传
    diyUpload ({ file }: { file: Blob }) {
      this.uploadBegin()
      return upload(file, ({ loaded, total }: { loaded: number; total: number }) => {
        this.uploadProgress(Math.floor(loaded * 100 / total))
      }).then(({ data }) => {
        if (data.code === '000000') {
          this.uploadEnd(true, data.data.name)
          this.$message.success('上传成功')
          return data
        }
        this.uploadEnd(false, '')
        this.$message.error('上传失败')
      })
    },
    beforeAvatarUpload (file: Blob) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!(isJPG || isPNG)) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return (isJPG || isPNG) && isLt2M
    }
  }
})
</script>
<style lang="scss" scoped>
.avatar-uploader ::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader ::v-deep .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
